
function transformFlameData(flameArray) {
  const result = {};

  // let depth = 0;
  const maxDepth = Math.max(...flameArray.map((item) => item.depth));

  flameArray.forEach((item) => {
    item.name = item.funcName;
    item.value = item.endPosition - item.startPosition;
  });
  const recursiveGenerateTreeData = (depth, sourceData, targetData) => {
    if (depth > maxDepth) {
      return;
    }
    if (depth === 0) {
      targetData.name = sourceData[0].funcName;
      targetData.value =
        sourceData[0].endPosition - sourceData[0].startPosition;
      targetData.maxDepth = maxDepth;
      targetData.maxValue =  targetData.value
      targetData.children = sourceData.filter(
        (item) => item.depth === depth + 1
      );

      targetData.children.forEach((item) => {
        item.maxValue = targetData.value;
        recursiveGenerateTreeData(depth + 1, sourceData, item);
      });
    } else {
      const { endPosition, startPosition, depth } = targetData;
      // targetData.maxDepth =
      const children = sourceData.filter(
        (item) =>
          item.depth === depth + 1 &&
          item.startPosition >= startPosition &&
          item.endPosition <= endPosition
      );

      if (children.length) {
        targetData.children = children;
        targetData.children.forEach((item) => {
          item.maxValue = targetData.maxValue;
          recursiveGenerateTreeData(depth + 1, sourceData, item);
        });
      }
    }
  };
  recursiveGenerateTreeData(0, flameArray, result);
  return result;
}
self.onmessage = function ({ data }) {
  console.log("Worker: Message received from main script", data);
  const result = transformFlameData(data);
  postMessage(result);
};
onmessage = function ({ data }) {
  console.log("Worker: Message received from main script", data);
  const result = transformFlameData(data);
  postMessage(result);
};
